#include "EnemyMissile.h"
#include <QtOpenGL>
#include <QPainter>

namespace QtTutorial4
{
	/**
	* Constructor
	*/
	EnemyMissile::EnemyMissile(QGraphicsItem *parent):
			QGraphicsItem(parent),
			mTime(0),
			mExploded(false),
			mHitTarget(false)
	{
	}

	/**
	* Destructor
	*/
	EnemyMissile::~EnemyMissile()
	{
	}

	/**
	* Initializes the missile.
	*/
	void EnemyMissile::initialize(QString inAppDirectory)
	{
		mApplicationDirectory = inAppDirectory;
		mImage.load(inAppDirectory+"nui_input_point.png");
		setSize(QSizeF(35,35));
	}

	/**
	* Returns the bounding rectangle of this object.
	*/
	QRectF EnemyMissile::boundingRect() const
	{
		return QRectF(QPointF(-mSize.width(), -mSize.height()) * 0.5f, mSize);
	}	

	/**
	* Checks if a coordinate is inside this object.
	*/
	const bool EnemyMissile::isInside(QPointF inPos) const
	{
		return boundingRect().contains(mapFromParent(inPos));
	}

	/**
	* Updates the missile.
	*/
	void EnemyMissile::update(float inFrameTime)
	{
		QVector2D position(pos());
		QVector2D direction = mTargetPosition - position;
		direction.normalize();
		direction *= (inFrameTime*100.0f*scale());
		position += direction;
		
		if((position-mTargetPosition).lengthSquared() < 5.0 * 5.0 * scale())
		{
			mHitTarget = true;
		}

		// Rotate the missile over time.
		mTime += inFrameTime*35.0f;
		setRotation(mTime);

		setPos(position.toPointF());
	}

	/**
	* Draws the missile.
	*/
	void EnemyMissile::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget /* = 0 */)
	{
		painter->save();
		painter->setTransform(transform(), true);

		// Draw the mImage
		painter->drawImage(boundingRect(),mImage); 

		// If the missile is near the ground we will draw a circle indicating this.
		if((QVector2D(pos())-mTargetPosition).lengthSquared() < 400.0 * 400.0 * scale())
		{
			QPen pen(Qt::white);
			pen.setStyle(Qt::DotLine);
			pen.setWidth(2);
			pen.setCapStyle(Qt::RoundCap);
			painter->setPen(pen);
			painter->drawEllipse(QPointF(0, 0), mSize.width() * 0.55f, mSize.height() * 0.55f);
		}

		painter->restore();
	}
}